import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  timeout: 5000
})

// request interceptor
service.interceptors.request.use(
  config => {
    if (store.getters.token) {
      config.headers['token'] = getToken()
    }
    return config
  },
  error => {
    console.log(error)
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  response => {
    const res = response.data
    const { code, msg, message } = res

    if (code === 200) {
      return res
    }

    Message({
      message: msg || message || '错误',
      type: 'error',
      duration: 5 * 1000
    })

    if (code === 401) {
      // Unauthorized
      MessageBox.confirm('登录已失效，请重新登录', '提示', {
        confirmButtonText: '确定',
        type: 'warning'
      }).then(() => {
        store.dispatch('user/resetToken').then(() => {
          location.reload()
        })
      })
    }

    return Promise.reject(new Error(msg || message || '错误'))
  },
  error => {
    console.log('错误' + error) // for debugging
    Message({
      message: error.message || '未知的错误',
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default service
